package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.entity.TProdstock;
import com.wit.witmg.entity.TPurchase;
import com.wit.witmg.mapper.TProdstockMapper;
import com.wit.witmg.service.ITProdstockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2025-01-15
 */
@Service
public class TProdstockServiceImpl extends ServiceImpl<TProdstockMapper, TProdstock> implements ITProdstockService {

    @Override
    public Object add(HttpServletRequest request, String json) {
        TProdstock t= JSON.parseObject(json,TProdstock.class);
        if(t.getId()>0){
            t.setQt(null);
            t.setPqt(null);
            t.setAmount(null);
            boolean bl=  updateById(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_200);
            }
        }else{
            t.setDate(new Date());
            boolean bl= save(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }
        return JsonResult.success(t);
    }

    @Override
    public Object get(HttpServletRequest request, Integer id,Integer oid, String store, String size, String bn) {
        //参数：store返回数组；bn、size模糊查询返回数组,id返回一条。
        QueryWrapper<TProdstock> qw=new QueryWrapper<>();
        if(id!=null){
            qw.eq("id",id);
            qw.last("limit 1");
            return JsonResult.success(getOne(qw));
        }
        if(oid!=null){//oid时，按库存数量从小到大返回数组
            qw.eq("oid",oid);
            qw.orderByAsc("qt");
            return JsonResult.success(list(qw));
        }
        if(store!=null){
            qw.eq("store",store);
            return JsonResult.success(list(qw));
        }
        if(size!=null){
            qw.like("size",size);
            return JsonResult.success(list(qw));
        }
        if(bn!=null){
            qw.like("bn",bn);
            qw.orderByAsc("bn");
            return JsonResult.success(list(qw));
        }
        return JsonResult.error(ErrorCode.ERR_200);
    }

    @Override
    public Object del(HttpServletRequest request, Integer id) {
        boolean bl= removeById(id);
        if(bl) {
            return JsonResult.success();
        }
        return JsonResult.error(ErrorCode.ERR_200);
    }
}
